#!/usr/bin/env python
# -*- coding: UTF-8 -*-


from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.core.files import File
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError

import sys

from psp.models import *


def getDateList():
    meetingDates = Poll.objects.getMeetingDates()
    retVal = meetingDates

    try:
        ds = MpDayStats.objects.all().order_by('-date')
        recentDate = ds[0].date
        i = 0
        for md in meetingDates:
            if md > recentDate:
                retVal = meetingDates[i:]
                print "Starting from: %d %d %d" % ( retVal[0].year,
                                                    retVal[0].month,
                                                    retVal[0].day
                                                )
                break
            i = i + 1

    except:
        print "Starting from the begining %d %d %d" % ( retVal[0].year,
                                                        retVal[0].month,
                                                        retVal[0].day
                                                    )

    return retVal


def main():
    dates = getDateList()

    for d in dates:
        print "Counting stats for: %s" % d.strftime("%d. %B %Y")
        MpDayStats.objects.createStatsForDay(d)
        for stat in MpDayStats.objects.all().filter(date = d):
            stat.save()

        print "done\n"

    return 0


if __name__ == '__main__':
    main()
    sys.exit()
